<script setup lang="ts">
import { ref, onMounted, toRaw } from "vue";
import { ElMessage, ElMessageBox, ElTable } from "element-plus";
import Searchbox from "@/views/components/searchbox/Searchbox.vue";
import { getDeptServerListApi, deleteDeptServerApi, DeptServerModel } from "@/api/clusters/deptServer";
import AddDeptServer from './component/add.vue';
import { pageSizeOptions } from "@/utils/appCommon/appCommonOptions/app";
import { useRoute } from "vue-router";
import { useUserStore } from "@/store/modules/user";
import { storeToRefs } from "pinia";
import { useLogic } from "@/views/system/user/logic/logic";
import { useI18n } from "vue-i18n";

defineOptions({
  name: "dept-server"
});
const {t} = useI18n();
const pageSizeOps = ref(pageSizeOptions)
const route = useRoute();
const storeInfo = useUserStore()
const {deptId}= storeToRefs(storeInfo)

// 搜索处理 - 增加搜索参数存储
const searchParams = ref({
  deptId: deptId.value,  //初始部门id
  serverKey: undefined,
  type: undefined,
  page:1,
  pageSize:20,
});

const {deptTreeList,getDeptTree}  = useLogic()
onMounted( async ()=>{
  await getDeptTree()
})

// 搜索字段配置
const searchFields = ref([
  {
    prop: 'deptId',
    name:  t("products.devicePage.deptId"),
    type: 'cascader',
    cascaderOptions: deptTreeList,
    clearable: true,
    isHidden: false,
    ops: {
      valueField: 'id',
      labelField: 'name',
      emitPath: false,
      checkStrictly: true
    }
  },
  {
    prop: "serverKey",
    name: t('clusters.deptServerPage.serverKey'),
    type: "input",
    placeholder: "",
  },
  {
    prop: "type",
    name: t('clusters.deptServerPage.type'),
    type: "input",
    placeholder: "",
  },
]);

// 表格数据
const tableData = ref<DeptServerModel[]>([]);
const total = ref(0);
const loading = ref(false);

// 加载数据
const loadData = async () => {
  loading.value = true;
  try {
    const params = {
      ...searchParams.value
    };
    const response = await getDeptServerListApi(params);
    if (response.code === 0) {
      tableData.value = response.data?.list || [];
      total.value = response.data?.total || 0;
    } else {
      ElMessage.error(response.msg || '获取数据失败');
    }
  } catch (error) {
    total.value = 0;
    ElMessage.error('获取数据失败');
  } finally {
    total.value = 0;
    loading.value = false;
  }
};

// 初始加载
onMounted(() => {
  loadData();
});

// 分页变化处理
const handlePaginationSizeChange = (pageSize: number) => {
  console.log(pageSize);
  searchParams.value.pageSize = pageSize;
  loadData();
};
const handlePaginationPageChange = (page: number) => {
  console.log(page);
  searchParams.value.page = page;
  loadData();
};

// 删除操作
const handleDelete = async (id: number) => {
  try {
    // 显示确认对话框
    await ElMessageBox.confirm(
      t('clusters.deptServerPage.deleteConfirm'),
      t('clusters.deptServerPage.deleteTitle'),
      {
        confirmButtonText: t('buttons.confirm'),
        cancelButtonText: t('buttons.cancel'),
        type: 'warning'
      }
    );

    const response = await deleteDeptServerApi(id);
    if (response.code === 0) {
      ElMessage.success(t('clusters.deptServerPage.deleteSuccess'));
      await loadData();
    } else {
      ElMessage.error(response.msg || t('clusters.deptServerPage.deleteFail'));
    }
  } catch (error) {
    // 用户取消或其他错误，不做任何操作
    console.log('删除已取消');
  }
};

// 新增弹框控制
const addDialogVisible = ref(false);

const handleChange = (e: any) => {
  console.log(e)
  Object.keys(e).forEach(key => {
    searchParams.value[key] = e[key];
  });
}
const handleSearch = async (e:any) => {
  console.log(e)
  Object.keys(e).forEach(key => {
    searchParams.value[key] = e[key];
  });
  await loadData();
}
const handleReset = (e:any) => {
  console.log(e)
}
</script>

<template>
  <el-card shadow="never">
    <template #header>
      <div class="card-header">
        <Searchbox
          :fields= searchFields
          :initialValues="searchParams"
          :maxVisibleFields=1
          @change="handleChange"
          @search="handleSearch"
          @reset="handleReset"
        />
      </div>
    </template>

    <div class="button-area">
      <el-button type="primary" @click="addDialogVisible = true">
        {{ t('clusters.deptServerPage.addButton') }}
      </el-button>
    </div>

    <el-table :data="tableData" v-loading="loading" border>
      <el-table-column prop="deptName" :label="t('clusters.deptServerPage.deptName')" width="180" />
      <el-table-column prop="serverKey" :label="t('clusters.deptServerPage.serverKey')" width="180" />
      <el-table-column prop="type" :label="t('clusters.deptServerPage.type')" />
      <el-table-column prop="remark" :label="t('clusters.deptServerPage.remark')" />
      <el-table-column prop="createdAt" :label="t('clusters.deptServerPage.createdAt')" width="180" />
      <el-table-column :label="t('clusters.deptServerPage.action')" width="120">
        <template #default="{ row }">
          <el-button
            type="danger"
            size="small"
            @click="handleDelete(row.id)"
          >
            {{ t('clusters.deptServerPage.deleteButton') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-model:current-page="searchParams.page"
      v-model:page-size="searchParams.pageSize"
      :page-sizes="pageSizeOps"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handlePaginationSizeChange"
      @current-change="handlePaginationPageChange"
    />

    <AddDeptServer v-model:visible="addDialogVisible" @success="loadData" />
  </el-card>
</template>

<style scoped lang="scss">

</style>
